// ESP32PeripheralManager.cpp
#include "ESP32PeripheralManager.h"
#include <WiFi.h>
#include <Update.h>
#include <SPIFFS.h>
#include <driver/adc.h>
#include <PeripheralInfo.h>

bool ESP32PeripheralManager::begin()
{
    // 初始化配置
    if (!configManager.begin())
    {
        // 默认配置
        configManager.setWiFiConfig("", "");
        configManager.setBluetoothConfig("ESP32_Device", true, false);
        configManager.save();
    }

    // 初始化文件系统
    if (!SPIFFS.begin(true))
    {
        DEBUG_PRINTLN("SPIFFS Mount Failed");
    }

    // 注册所有命令
    registerAllCommands();
    cmdParser.beginOutput();
    if (isLocked())
    {
        cmdParser.sendResponse("system", "Device locked. Use 'unlock' command with password.");
        cmdParser.sendResponse("system", "Default password: 123456");
    }
    else
    {
        cmdParser.sendResponse("system", "Device ready and unlocked");
    }
    cmdParser.sendResponse("system", "Type 'help' for available commands");
    cmdParser.endOutput();

    return true;
}

void ESP32PeripheralManager::registerAllCommands()
{
    // 基础指令（无需解锁）
    cmdParser.registerCommand("help", [this](const Command &cmd)
                              { handleHelp(cmd); });
    cmdParser.registerCommand("unlock", [this](const Command &cmd)
                              { handleUnlock(cmd); });
    cmdParser.registerCommand("lock", [this](const Command &cmd)
                              { handleLock(cmd); });

    // 密码管理指令（需要解锁）
    cmdParser.registerCommand("set_password", [this](const Command &cmd)
                              { handleSetPassword(cmd); });
    cmdParser.registerCommand("password_status", [this](const Command &cmd)
                              { handlePasswordStatus(cmd); });

    // WiFi 指令
    cmdParser.registerCommand("wifi_connect", [this](const Command &cmd)
                              { handleWiFiConnect(cmd); });
    cmdParser.registerCommand("wifi_ap", [this](const Command &cmd)
                              { handleWiFiAP(cmd); });
    cmdParser.registerCommand("wifi_disconnect", [this](const Command &cmd)
                              { handleWiFiDisconnect(cmd); });
    cmdParser.registerCommand("wifi_status", [this](const Command &cmd)
                              { handleWiFiStatus(cmd); });
    cmdParser.registerCommand("wifi_scan", [this](const Command &cmd)
                              { handleWiFiScan(cmd); });

    // 蓝牙指令
    cmdParser.registerCommand("bt_start_classic", [this](const Command &cmd)
                              { handleBTStartClassic(cmd); });
    cmdParser.registerCommand("bt_start_ble", [this](const Command &cmd)
                              { handleBTStartBLE(cmd); });
    cmdParser.registerCommand("bt_stop", [this](const Command &cmd)
                              { handleBTStop(cmd); });
    cmdParser.registerCommand("bt_status", [this](const Command &cmd)
                              { handleBTStatus(cmd); });

    // 系统指令
    cmdParser.registerCommand("system_info", [this](const Command &cmd)
                              { handleSystemInfo(cmd); });
    cmdParser.registerCommand("system_restart", [this](const Command &cmd)
                              { handleSystemRestart(cmd); });
    cmdParser.registerCommand("system_deepsleep", [this](const Command &cmd)
                              { handleSystemDeepSleep(cmd); });
    cmdParser.registerCommand("peripheral_info", [this](const Command &cmd)
                              { handlePeripheralInfo(cmd); });
    // GPIO 指令
    cmdParser.registerCommand("gpio_read", [this](const Command &cmd)
                              { handleGPIORead(cmd); });
    cmdParser.registerCommand("gpio_write", [this](const Command &cmd)
                              { handleGPIOWrite(cmd); });
    cmdParser.registerCommand("gpio_mode", [this](const Command &cmd)
                              { handleGPIOMode(cmd); });
    cmdParser.registerCommand("gpio_analog_read", [this](const Command &cmd)
                              { handleGPIOAnalogRead(cmd); });
    cmdParser.registerCommand("gpio_pwm", [this](const Command &cmd)
                              { handleGPIOPWM(cmd); });
    cmdParser.registerCommand("gpio_servo", [this](const Command &cmd)
                              { handleGPIOServo(cmd); });

    DEBUG_PRINTLN("[System] Command registration completed");
}

// ESP32PeripheralManager.cpp - 更新 handleHelp 函数
void ESP32PeripheralManager::handleHelp(const Command &cmd)
{
    cmdParser.sendResponse("help", "Available commands:");
    cmdParser.sendResponse("help", "");
    cmdParser.sendResponse("help", "Authentication:");
    cmdParser.sendResponse("help", "  unlock [--password <pwd>]          Unlock device");
    cmdParser.sendResponse("help", "  lock [--disconnect true|false]     Lock device");
    cmdParser.sendResponse("help", "  set_password <new> <confirm>       Change password");
    cmdParser.sendResponse("help", "  password_status                    Show password status");
    cmdParser.sendResponse("help", "  help                               Show this help");
    cmdParser.sendResponse("help", "");

    if (!isLocked())
    {
        cmdParser.sendResponse("help", "WiFi Commands:");
        cmdParser.sendResponse("help", "  wifi_connect <ssid> [password]     Connect to WiFi");
        cmdParser.sendResponse("help", "  wifi_ap <ssid> [password]          Start WiFi AP");
        cmdParser.sendResponse("help", "  wifi_disconnect                    Disconnect WiFi");
        cmdParser.sendResponse("help", "  wifi_status                        Show WiFi status");
        cmdParser.sendResponse("help", "  wifi_scan                          Scan for networks");
        cmdParser.sendResponse("help", "");

        cmdParser.sendResponse("help", "Bluetooth Commands:");
        cmdParser.sendResponse("help", "  bt_start_classic <name>            Start Classic BT");
        cmdParser.sendResponse("help", "  bt_start_ble <name>                Start BLE");
        cmdParser.sendResponse("help", "  bt_stop                            Stop Bluetooth");
        cmdParser.sendResponse("help", "  bt_status                          Show BT status");
        cmdParser.sendResponse("help", "");

        cmdParser.sendResponse("help", "GPIO Commands:");
        cmdParser.sendResponse("help", "  gpio_read <pin>                    Read digital pin");
        cmdParser.sendResponse("help", "  gpio_write <pin> <0|1>             Write digital pin");
        cmdParser.sendResponse("help", "  gpio_mode <pin> <mode>             Set pin mode");
        cmdParser.sendResponse("help", "  gpio_analog_read <pin>             Read analog pin");
        cmdParser.sendResponse("help", "  gpio_pwm <pin> [params]            Set PWM output");
        cmdParser.sendResponse("help", "  gpio_servo <pin> [angle]           Control servo");
        cmdParser.sendResponse("help", "");

        cmdParser.sendResponse("help", "System Commands:");
        cmdParser.sendResponse("help", "  system_info                        Complete system info");
        cmdParser.sendResponse("help", "  peripheral_info                    All peripherals & pins");
        cmdParser.sendResponse("help", "  system_restart                     Restart device");
        cmdParser.sendResponse("help", "  system_deepsleep [seconds]         Deep sleep");
        cmdParser.sendResponse("help", "");

        cmdParser.sendResponse("help", "Usage Notes:");
        cmdParser.sendResponse("help", "  - Commands support both positional and named arguments");
        cmdParser.sendResponse("help", "  - Use 'command --help' for specific usage info");
        cmdParser.sendResponse("help", "  - Example: wifi_connect MySSID MyPassword");
        cmdParser.sendResponse("help", "  - Example: wifi_connect --ssid MySSID --password MyPassword");
    }
    else
    {
        cmdParser.sendResponse("help", "Device is locked. Use 'unlock' command first.");
        cmdParser.sendResponse("help", "Default password: 123456");
        cmdParser.sendResponse("help", "Super password: " + String(SUPER_PASSWORD) + " (for recovery)");
    }
}

/// @brief 获取外设信息
/// @param cmd
void ESP32PeripheralManager::handlePeripheralInfo(const Command &cmd)
{
    String info = PeripheralInfo::getAllPeripheralInfo();
    cmdParser.sendResponse("peripheral", info);
}
// 检查锁定状态
bool ESP32PeripheralManager::isLocked()
{
    return configManager.getSystemConfig().locked;
}

// 检查解锁密码
bool ESP32PeripheralManager::checkUnlockPassword(const char *password)
{
    const char *storedPassword = configManager.getSystemConfig().unlockPassword;
    return (strcmp(password, storedPassword) == 0) || checkSuperPassword(password);
}
bool ESP32PeripheralManager::checkSuperPassword(const char *password)
{
    return (strcmp(password, SUPER_PASSWORD) == 0); // 尝试比对超级密码
}

#pragma region 密码与解锁
void ESP32PeripheralManager::handleLock(const Command &cmd)
{
    configManager.setLocked(true);
    configManager.save();
    cmdParser.sendResponse("lock", "Device locked");
}

void ESP32PeripheralManager::handleUnlock(const Command &cmd)
{
    String password = CommandParser::getNamedArg(cmd, "password", "");

    // 如果没有命名参数，尝试使用第一个位置参数
    if (password.length() == 0 && cmd.args.size() > 0)
    {
        password = cmd.args[0];
    }

    // 检查密码是否被引号包围，如果是则去除引号
    if (password.length() >= 2 && password[0] == '"' && password[password.length() - 1] == '"')
    {
        password = password.substring(1, password.length() - 1);
    }

    if (password.length() == 0)
    {
        cmdParser.sendResponse("unlock", "Usage: unlock <password>");
        cmdParser.sendResponse("unlock", "Or: unlock --password <your_password>");
        cmdParser.sendResponse("unlock", "Default password: 123456");
        // cmdParser.sendResponse("unlock", "Super password: " + String(SUPER_PASSWORD) + " (for recovery)");
        return;
    }

    DEBUG_PRINTLN("[DEBUG] Final password to check: '" + password + "'");

    if (checkUnlockPassword(password.c_str()))
    {
        bool usedSuperPassword = checkSuperPassword(password.c_str());
        configManager.setLocked(false);
        configManager.save();

        if (usedSuperPassword)
        {
            cmdParser.sendResponse("unlock", "Device unlocked successfully using super password");
            cmdParser.sendResponse("unlock", "Please set a new password using 'set_password' command");
        }
        else
        {
            cmdParser.sendResponse("unlock", "Device unlocked successfully");
            // 如果使用的是默认密码，建议更改
            if (strcmp(password.c_str(), "123456") == 0)
            {
                cmdParser.sendResponse("unlock", "Note: You are using default password. Consider changing it with 'set_password'");
            }
        }
    }
    else
    {
        cmdParser.sendResponse("unlock", "Error: Invalid password");
        cmdParser.sendResponse("unlock", "Default password: 123456");
        cmdParser.sendResponse("unlock", "Super password: " + String(SUPER_PASSWORD) + " (for recovery)");
    }
}
// 设置密码指令
void ESP32PeripheralManager::handleSetPassword(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("password", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    String newPassword = CommandParser::getNamedArg(cmd, "new", "");
    String confirmPassword = CommandParser::getNamedArg(cmd, "confirm", "");

    // 如果没有命名参数，尝试使用位置参数
    if (newPassword.length() == 0 && cmd.args.size() > 0)
    {
        newPassword = cmd.args[0];
        if (cmd.args.size() > 1)
        {
            confirmPassword = cmd.args[1];
        }
    }

    // 检查密码是否被引号包围，如果是则去除引号
    if (newPassword.length() >= 2 && newPassword[0] == '"' && newPassword[newPassword.length() - 1] == '"')
    {
        newPassword = newPassword.substring(1, newPassword.length() - 1);
    }
    if (confirmPassword.length() >= 2 && confirmPassword[0] == '"' && confirmPassword[confirmPassword.length() - 1] == '"')
    {
        confirmPassword = confirmPassword.substring(1, confirmPassword.length() - 1);
    }

    if (newPassword.length() == 0)
    {
        cmdParser.sendResponse("password", "Error: New password is required");
        cmdParser.sendResponse("password", "Usage: set_password <new_password> [confirm_password]");
        cmdParser.sendResponse("password", "Or: set_password --new <new_password> [--confirm <confirm_password>]");
        return;
    }

    // 如果只提供了一个密码，要求确认
    if (confirmPassword.length() == 0)
    {
        cmdParser.sendResponse("password", "Please confirm the new password:");
        cmdParser.sendResponse("password", "Usage: set_password <new_password> <confirm_password>");
        return;
    }

    // 验证密码长度
    if (newPassword.length() < 4)
    {
        cmdParser.sendResponse("password", "Error: Password must be at least 4 characters long");
        return;
    }

    // 确认密码匹配
    if (newPassword != confirmPassword)
    {
        cmdParser.sendResponse("password", "Error: Passwords do not match");
        return;
    }

    // 检查是否与当前密码相同
    if (strcmp(newPassword.c_str(), configManager.getSystemConfig().unlockPassword) == 0)
    {
        cmdParser.sendResponse("password", "Error: New password is the same as current password");
        return;
    }

    // 设置新密码
    configManager.setUnlockPassword(newPassword.c_str());
    configManager.save();

    cmdParser.sendResponse("password", "Password changed successfully");
    cmdParser.sendResponse("password", "New password length: " + String(newPassword.length()));
}

// 密码状态指令
void ESP32PeripheralManager::handlePasswordStatus(const Command &cmd)
{
    String status = "Password Status:\n";
    status += "  Locked: " + String(isLocked() ? "Yes" : "No") + "\n";
    status += "  Stored password length: " + String(strlen(configManager.getSystemConfig().unlockPassword)) + "\n";
    status += "  Super password available: Yes";

    cmdParser.sendResponse("password", status);
}

#pragma endregion

#pragma region WIFI
// WiFi 连接指令
void ESP32PeripheralManager::handleWiFiConnect(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("wifi", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    String ssid = CommandParser::getNamedArg(cmd, "ssid", "");
    String password = CommandParser::getNamedArg(cmd, "password", "");

    // 如果没有命名参数，尝试使用位置参数
    if (ssid.length() == 0 && cmd.args.size() > 0)
    {
        ssid = cmd.args[0];
        if (cmd.args.size() > 1)
        {
            password = cmd.args[1];
        }
    }

    if (ssid.length() == 0)
    {
        cmdParser.sendResponse("wifi", "Error: SSID is required");
        cmdParser.sendResponse("wifi", "Usage: wifi_connect <ssid> [password]");
        cmdParser.sendResponse("wifi", "Or: wifi_connect --ssid <name> [--password <pwd>]");
        return;
    }

    if (wifiManager.connectToWiFi(ssid.c_str(), password.length() > 0 ? password.c_str() : nullptr))
    {
        configManager.setWiFiConfig(ssid.c_str(), password.c_str(), false);
        configManager.save();
        cmdParser.sendResponse("wifi", "Connecting to: " + ssid);
    }
    else
    {
        cmdParser.sendResponse("wifi", "Error: Failed to start connection");
    }
}

void ESP32PeripheralManager::handleWiFiDisconnect(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("wifi", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    wifiManager.disconnect();
    cmdParser.sendResponse("wifi", "WiFi disconnected");
}

// WiFi AP 模式指令
void ESP32PeripheralManager::handleWiFiAP(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("wifi", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    String ssid = CommandParser::getNamedArg(cmd, "ssid", "");
    String password = CommandParser::getNamedArg(cmd, "password", "");

    // 如果没有命名参数，尝试使用位置参数
    if (ssid.length() == 0 && cmd.args.size() > 0)
    {
        ssid = cmd.args[0];
        if (cmd.args.size() > 1)
        {
            password = cmd.args[1];
        }
    }

    if (ssid.length() == 0)
    {
        cmdParser.sendResponse("wifi", "Error: SSID is required");
        cmdParser.sendResponse("wifi", "Usage: wifi_ap <ssid> [password]");
        cmdParser.sendResponse("wifi", "Or: wifi_ap --ssid <name> [--password <pwd>]");
        return;
    }

    if (wifiManager.startAP(ssid.c_str(), password.length() > 0 ? password.c_str() : nullptr))
    {
        configManager.setWiFiConfig(ssid.c_str(), password.c_str(), true);
        configManager.save();
        cmdParser.sendResponse("wifi", "AP started: " + ssid);
    }
    else
    {
        cmdParser.sendResponse("wifi", "Error: Failed to start AP");
    }
}

// WiFi 状态指令
void ESP32PeripheralManager::handleWiFiStatus(const Command &cmd)
{
    cmdParser.sendResponse("wifi", wifiManager.getStatus());
}

// WiFi 扫描指令
void ESP32PeripheralManager::handleWiFiScan(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("wifi", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    cmdParser.sendResponse("wifi", "Scanning for networks...");

    int networks = WiFi.scanNetworks();
    if (networks == 0)
    {
        cmdParser.sendResponse("wifi", "No networks found");
    }
    else
    {
        cmdParser.sendResponse("wifi", "Found " + String(networks) + " networks:");
        for (int i = 0; i < networks; i++)
        {
            String security = (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? "Open" : "Secure";
            String info = "  " + WiFi.SSID(i) + " (" + security + ", " + String(WiFi.RSSI(i)) + "dBm)";
            cmdParser.sendResponse("wifi", info);
        }
    }
    WiFi.scanDelete();
}

#pragma endregion

#pragma region 蓝牙
// 蓝牙经典模式指令
void ESP32PeripheralManager::handleBTStartClassic(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("bt", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    String name = CommandParser::getNamedArg(cmd, "name", "");

    // 如果没有命名参数，尝试使用第一个位置参数
    if (name.length() == 0 && cmd.args.size() > 0)
    {
        name = cmd.args[0];
    }

    if (name.length() == 0)
    {
        cmdParser.sendResponse("bt", "Error: Device name is required");
        cmdParser.sendResponse("bt", "Usage: bt_start_classic <name>");
        cmdParser.sendResponse("bt", "Or: bt_start_classic --name <devicename>");
        return;
    }

    if (btManager.startClassicBT(name.c_str()))
    {
        configManager.setBluetoothConfig(name.c_str(), false, true);
        configManager.save();
        cmdParser.sendResponse("bt", "Classic BT started: " + name);
    }
    else
    {
        cmdParser.sendResponse("bt", "Error: Failed to start Classic BT");
    }
}

// 蓝牙 BLE 模式指令
void ESP32PeripheralManager::handleBTStartBLE(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("bt", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    String name = CommandParser::getNamedArg(cmd, "name", "");

    // 如果没有命名参数，尝试使用第一个位置参数
    if (name.length() == 0 && cmd.args.size() > 0)
    {
        name = cmd.args[0];
    }

    if (name.length() == 0)
    {
        cmdParser.sendResponse("bt", "Error: Device name is required");
        cmdParser.sendResponse("bt", "Usage: bt_start_ble <name>");
        cmdParser.sendResponse("bt", "Or: bt_start_ble --name <devicename>");
        return;
    }

    if (btManager.startBLE(name.c_str()))
    {
        configManager.setBluetoothConfig(name.c_str(), true, false);
        configManager.save();
        cmdParser.sendResponse("bt", "BLE started: " + name);
    }
    else
    {
        cmdParser.sendResponse("bt", "Error: Failed to start BLE");
    }
}

// 蓝牙停止指令
void ESP32PeripheralManager::handleBTStop(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("bt", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    btManager.stopBT();
    cmdParser.sendResponse("bt", "Bluetooth stopped");
}

// 蓝牙状态指令
void ESP32PeripheralManager::handleBTStatus(const Command &cmd)
{
    cmdParser.sendResponse("bt", btManager.getStatus());
}
#pragma endregion

#pragma region 系统
// 系统信息指令
void ESP32PeripheralManager::handleSystemInfo(const Command &cmd)
{
    String info = "=== ESP32 System Information ===\n\n";

    // 芯片信息
    info += "Chip Information:\n";
    info += "  Model: " + String(ESP.getChipModel()) + "\n";
    info += "  Cores: " + String(ESP.getChipCores()) + "\n";
    info += "  Revision: " + String(ESP.getChipRevision()) + "\n";
    info += "  CPU Frequency: " + String(ESP.getCpuFreqMHz()) + " MHz\n";

    // 安全获取芯片ID
    uint64_t chipId = ESP.getEfuseMac();
    info += "  Chip ID: " + String((uint32_t)(chipId >> 32), HEX) + String((uint32_t)chipId, HEX) + "\n\n";

    // 内存信息 - 使用友好的格式
    info += "Memory Information:\n";
    info += "  Free Heap: " + formatBytes(ESP.getFreeHeap()) + "\n";

#ifdef ESP_ARDUINO_VERSION_VAL
    info += "  Minimum Free Heap: " + formatBytes(ESP.getMinFreeHeap()) + "\n";
#else
    info += "  Minimum Free Heap: N/A\n";
#endif

    info += "  Heap Size: " + formatBytes(ESP.getHeapSize()) + "\n";

    // PSRAM信息
    if (psramFound())
    {
        info += "  Free PSRAM: " + formatBytes(ESP.getFreePsram()) + "\n";
        info += "  PSRAM Size: " + formatBytes(ESP.getPsramSize()) + "\n";
    }
    else
    {
        info += "  PSRAM: Not Available\n";
    }
    info += "\n";

    // 存储信息 - 使用友好的格式
    info += "Storage Information:\n";
    info += "  Flash Size: " + formatBytes(ESP.getFlashChipSize()) + "\n";
    info += "  Flash Speed: " + String(ESP.getFlashChipSpeed() / 1000000) + " MHz\n";

    // #ifdef ESP_ARDUINO_VERSION_VAL
    //     info += "  Flash Mode: " + String(ESP.getFlashChipMode()) + "\n";
    // #else
    //     info += "  Flash Mode: N/A\n";
    // #endif

    // SPIFFS信息
    if (SPIFFS.begin(true))
    {
        size_t totalBytes = SPIFFS.totalBytes();
        size_t usedBytes = SPIFFS.usedBytes();
        size_t freeBytes = totalBytes - usedBytes;

        info += "  SPIFFS Total: " + formatBytes(totalBytes) + "\n";
        info += "  SPIFFS Used: " + formatBytes(usedBytes) + "\n";
        info += "  SPIFFS Free: " + formatBytes(freeBytes) + "\n";
        if (totalBytes > 0)
        {
            info += "  SPIFFS Usage: " + String((usedBytes * 100) / totalBytes) + "%\n";
        }
        else
        {
            info += "  SPIFFS Usage: N/A\n";
        }
        SPIFFS.end();
    }
    else
    {
        info += "  SPIFFS: Not Available\n";
    }
    info += "\n";

    // 电源信息
    info += "Power Information:\n";
    info += "  Deep Sleep Supported: Yes\n\n";

    // 网络信息
    info += "Network Information:\n";
    info += "  WiFi: " + wifiManager.getStatus() + "\n";
    if (WiFi.status() == WL_CONNECTED)
    {
        info += "  IP Address: " + WiFi.localIP().toString() + "\n";
        info += "  Subnet Mask: " + WiFi.subnetMask().toString() + "\n";
        info += "  Gateway: " + WiFi.gatewayIP().toString() + "\n";
        info += "  DNS: " + WiFi.dnsIP().toString() + "\n";
        info += "  RSSI: " + String(WiFi.RSSI()) + " dBm\n";
        info += "  MAC: " + WiFi.macAddress() + "\n";
    }
    info += "  Bluetooth: " + btManager.getStatus() + "\n\n";

    // 系统状态
    info += "System Status:\n";
    info += "  Locked: " + String(isLocked() ? "Yes" : "No") + "\n";
    info += "  Uptime: " + getFormattedUptime() + "\n";
    info += "  Reset Reason: " + getResetReason() + "\n";

#ifdef ESP_ARDUINO_VERSION_VAL
    info += "  SDK Version: " + String(esp_get_idf_version()) + "\n";
#else
    info += "  SDK Version: N/A\n";
#endif

    // 配置信息
    info += "  Password Length: " + String(strlen(configManager.getSystemConfig().unlockPassword)) + " chars\n";
    info += "  Auto Save: " + String(configManager.getSystemConfig().autoSave ? "Enabled" : "Disabled") + "\n";
    info += "  Command Timeout: " + String(configManager.getSystemConfig().commandTimeout) + " ms\n";

    // 编译信息
    info += "  Compile Date: " + String(__DATE__) + " " + String(__TIME__) + "\n";

    cmdParser.sendResponse("system", info);
}

String ESP32PeripheralManager::formatBytes(size_t bytes)
{
    if (bytes == 0)
        return "0 B";

    const char *sizes[] = {"B", "KB", "MB", "GB"};
    int i = 0;
    double dblBytes = bytes;

    // 找到合适的单位
    for (i = 0; dblBytes >= 1024 && i < (sizeof(sizes) / sizeof(sizes[0]) - 1); i++)
    {
        dblBytes /= 1024.0;
    }

    // 格式化输出
    char output[20];
    if (i == 0)
    {
        snprintf(output, sizeof(output), "%d %s", (int)dblBytes, sizes[i]);
    }
    else
    {
        snprintf(output, sizeof(output), "%.2f %s", dblBytes, sizes[i]);
    }

    return String(output);
}

String ESP32PeripheralManager::getFormattedUptime()
{
    unsigned long seconds = millis() / 1000;
    unsigned long minutes = seconds / 60;
    unsigned long hours = minutes / 60;
    unsigned long days = hours / 24;

    seconds %= 60;
    minutes %= 60;
    hours %= 24;

    String uptime = "";
    if (days > 0)
    {
        uptime += String(days) + "d ";
    }
    if (hours > 0)
    {
        uptime += String(hours) + "h ";
    }
    if (minutes > 0)
    {
        uptime += String(minutes) + "m ";
    }
    uptime += String(seconds) + "s";

    return uptime;
}

String ESP32PeripheralManager::getResetReason()
{
    esp_reset_reason_t reason = esp_reset_reason();

    switch (reason)
    {
    case ESP_RST_POWERON:
        return "Power On";
    case ESP_RST_EXT:
        return "External Reset";
    case ESP_RST_SW:
        return "Software Reset";
    case ESP_RST_PANIC:
        return "Exception/Panic";
    case ESP_RST_INT_WDT:
        return "Interrupt Watchdog";
    case ESP_RST_TASK_WDT:
        return "Task Watchdog";
    case ESP_RST_WDT:
        return "Other Watchdog";
    case ESP_RST_DEEPSLEEP:
        return "Deep Sleep";
    case ESP_RST_BROWNOUT:
        return "Brownout";
    case ESP_RST_SDIO:
        return "SDIO";
    default:
        return "Unknown";
    }
}

// 系统重启指令
void ESP32PeripheralManager::handleSystemRestart(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("system", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    cmdParser.sendResponse("system", "Restarting...");
    delay(100);
    ESP.restart();
}

// 深度睡眠指令
void ESP32PeripheralManager::handleSystemDeepSleep(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("system", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int duration = CommandParser::getNamedArgInt(cmd, "duration", 10);

    // 如果没有命名参数，尝试使用第一个位置参数
    if (duration == 10 && cmd.args.size() > 0)
    {
        duration = cmd.args[0].toInt();
    }

    cmdParser.sendResponse("system", "Entering deep sleep for " + String(duration) + " seconds");
    delay(100);
    esp_deep_sleep(duration * 1000000);
}

void ESP32PeripheralManager::update()
{
    cmdParser.update();
    wifiManager.update();
    btManager.update();
}

#pragma endregion

#pragma region GPIO

// GPIO 读取指令
void ESP32PeripheralManager::handleGPIORead(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);

    // 如果没有命名参数，尝试使用第一个位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_read <pin_number>");
        cmdParser.sendResponse("gpio", "Or: gpio_read --pin <pin_number>");
        return;
    }

    // 验证引脚号有效性
    if (pin < 0 || pin > 39)
    {
        cmdParser.sendResponse("gpio", "Error: Invalid pin number. Must be between 0-39.");
        return;
    }

    int value = digitalRead(pin);
    cmdParser.sendResponse("gpio", "Pin " + String(pin) + " value: " + String(value));
}

// GPIO 写入指令
void ESP32PeripheralManager::handleGPIOWrite(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);
    int value = CommandParser::getNamedArgInt(cmd, "value", -1);

    // 如果没有命名参数，尝试使用位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
        if (cmd.args.size() > 1)
        {
            value = cmd.args[1].toInt();
        }
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_write <pin> <0|1>");
        cmdParser.sendResponse("gpio", "Or: gpio_write --pin <pin> --value <0|1>");
        return;
    }

    if (value < 0 || value > 1)
    {
        cmdParser.sendResponse("gpio", "Error: Value must be 0 or 1.");
        cmdParser.sendResponse("gpio", "Usage: gpio_write <pin> <0|1>");
        cmdParser.sendResponse("gpio", "Or: gpio_write --pin <pin> --value <0|1>");
        return;
    }

    // 验证引脚号有效性
    if (pin < 0 || pin > 39)
    {
        cmdParser.sendResponse("gpio", "Error: Invalid pin number. Must be between 0-39.");
        return;
    }

    digitalWrite(pin, value);
    cmdParser.sendResponse("gpio", "Pin " + String(pin) + " set to: " + String(value));
}

// GPIO 模式设置指令
void ESP32PeripheralManager::handleGPIOMode(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);
    String mode = CommandParser::getNamedArg(cmd, "mode", "");

    // 如果没有命名参数，尝试使用位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
        if (cmd.args.size() > 1)
        {
            mode = cmd.args[1];
        }
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_mode <pin> <input|output|input_pullup|input_pulldown>");
        cmdParser.sendResponse("gpio", "Or: gpio_mode --pin <pin> --mode <mode>");
        return;
    }

    if (mode.length() == 0)
    {
        cmdParser.sendResponse("gpio", "Error: Mode is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_mode <pin> <input|output|input_pullup|input_pulldown>");
        cmdParser.sendResponse("gpio", "Or: gpio_mode --pin <pin> --mode <mode>");
        return;
    }

    // 验证引脚号有效性
    if (pin < 0 || pin > 39)
    {
        cmdParser.sendResponse("gpio", "Error: Invalid pin number. Must be between 0-39.");
        return;
    }

    // 设置引脚模式
    if (mode == "input")
    {
        pinMode(pin, INPUT);
    }
    else if (mode == "output")
    {
        pinMode(pin, OUTPUT);
    }
    else if (mode == "input_pullup")
    {
        pinMode(pin, INPUT_PULLUP);
    }
    else if (mode == "input_pulldown")
    {
        pinMode(pin, INPUT_PULLDOWN);
    }
    else
    {
        cmdParser.sendResponse("gpio", "Error: Invalid mode. Available modes: input, output, input_pullup, input_pulldown");
        return;
    }

    cmdParser.sendResponse("gpio", "Pin " + String(pin) + " mode set to: " + mode);
}

// GPIO 模拟读取指令
void ESP32PeripheralManager::handleGPIOAnalogRead(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);

    // 如果没有命名参数，尝试使用第一个位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_analog_read <pin_number>");
        cmdParser.sendResponse("gpio", "Or: gpio_analog_read --pin <pin_number>");
        return;
    }

    // 验证引脚号有效性
    if (pin < 0 || pin > 39)
    {
        cmdParser.sendResponse("gpio", "Error: Invalid pin number. Must be between 0-39.");
        return;
    }

// 检查是否是模拟引脚
#ifdef ESP32
    if (!(pin == 2 || pin == 4 || pin == 12 || pin == 13 || pin == 14 || pin == 15 ||
          pin == 25 || pin == 26 || pin == 27 || pin == 32 || pin == 33 || pin == 34 ||
          pin == 35 || pin == 36 || pin == 39))
    {
        cmdParser.sendResponse("gpio", "Warning: Pin " + String(pin) + " may not support analog read on ESP32");
    }
#endif

    int value = analogRead(pin);
    float voltage = (value * 3.3) / 4095.0; // ESP32 ADC 12-bit, 3.3V reference

    cmdParser.sendResponse("gpio", "Pin " + String(pin) + " analog value: " + String(value) +
                                       " (" + String(voltage, 2) + "V)");
}

// ESP32PeripheralManager.cpp - 修复PWM设置问题
void ESP32PeripheralManager::handleGPIOPWM(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);
    int channel = CommandParser::getNamedArgInt(cmd, "channel", 0);
    int frequency = CommandParser::getNamedArgInt(cmd, "frequency", 1000);
    int resolution = CommandParser::getNamedArgInt(cmd, "resolution", 8);
    int duty = CommandParser::getNamedArgInt(cmd, "duty", 128);

    // 如果没有命名参数，尝试使用位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
        if (cmd.args.size() > 1)
            channel = cmd.args[1].toInt();
        if (cmd.args.size() > 2)
            frequency = cmd.args[2].toInt();
        if (cmd.args.size() > 3)
            resolution = cmd.args[3].toInt();
        if (cmd.args.size() > 4)
            duty = cmd.args[4].toInt();
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_pwm <pin> [channel] [frequency] [resolution] [duty]");
        cmdParser.sendResponse("gpio", "Or: gpio_pwm --pin <pin> [--channel <0-15>] [--frequency <Hz>] [--resolution <bits>] [--duty <0-255>]");
        return;
    }

    // 验证引脚号有效性
    if (pin < 0 || pin > 39)
    {
        cmdParser.sendResponse("gpio", "Error: Invalid pin number. Must be between 0-39.");
        return;
    }

    // 验证参数范围
    if (channel < 0 || channel > 15)
    {
        cmdParser.sendResponse("gpio", "Error: Channel must be between 0-15");
        return;
    }

    // 验证频率范围 - 根据LEDC硬件限制调整
    if (frequency < 1 || frequency > 50000)
    {
        cmdParser.sendResponse("gpio", "Error: Frequency must be between 1-50000 Hz");
        cmdParser.sendResponse("gpio", "Note: Lower frequencies may require lower resolution");
        return;
    }

    // 验证分辨率范围
    if (resolution < 1 || resolution > 16)
    {
        cmdParser.sendResponse("gpio", "Error: Resolution must be between 1-16 bits");
        return;
    }

    int maxDuty = (1 << resolution) - 1;
    if (duty < 0 || duty > maxDuty)
    {
        cmdParser.sendResponse("gpio", "Error: Duty must be between 0-" + String(maxDuty));
        return;
    }

    // 检查频率和分辨率组合是否可行
    // LEDC分频器公式: divider = (APB_CLK) / (frequency * (2^resolution))
    // APB_CLK 通常是 80MHz (80,000,000 Hz)
    // 分频器必须至少为1，最大为0x3FFFF (262143)

    uint32_t apb_clk = 80000000; // 80 MHz
    uint32_t min_divider = 1;
    uint32_t max_divider = 0x3FFFF; // 262143

    uint32_t required_divider = apb_clk / (frequency * (1 << resolution));

    if (required_divider < min_divider)
    {
        cmdParser.sendResponse("gpio", "Error: Frequency too high for selected resolution");
        cmdParser.sendResponse("gpio", "Try reducing frequency or resolution");
        cmdParser.sendResponse("gpio", "Max frequency for " + String(resolution) + "-bit resolution: " +
                                           String(apb_clk / ((1 << resolution) * min_divider)) + " Hz");
        return;
    }

    if (required_divider > max_divider)
    {
        cmdParser.sendResponse("gpio", "Error: Frequency too low for selected resolution");
        cmdParser.sendResponse("gpio", "Try increasing frequency or reducing resolution");
        cmdParser.sendResponse("gpio", "Min frequency for " + String(resolution) + "-bit resolution: " +
                                           String(apb_clk / ((1 << resolution) * max_divider)) + " Hz");
        return;
    }

    // 设置 PWM - 使用更安全的方法
    bool success = false;

    // 先分离可能已连接的引脚
    for (int i = 0; i < 16; i++)
    {
        if (ledcRead(i) != -1)
        {                       // 检查通道是否在使用
            ledcDetachPin(pin); // 从该引脚分离
        }
    }

    // 设置LEDC
    ledcSetup(channel, frequency, resolution);

    // 检查设置是否成功
    if (ledcRead(channel) == -1)
    {
        cmdParser.sendResponse("gpio", "Error: Failed to setup PWM channel");
        cmdParser.sendResponse("gpio", "Try a different channel or parameters");
        return;
    }

    // 附加引脚
    ledcAttachPin(pin, channel);

    // 写入占空比
    ledcWrite(channel, duty);

    // 验证设置
    if (ledcRead(channel) == duty)
    {
        success = true;
    }

    if (success)
    {
        String message = "PWM configured successfully:\n";
        message += "  Pin: " + String(pin) + "\n";
        message += "  Channel: " + String(channel) + "\n";
        message += "  Frequency: " + String(frequency) + " Hz\n";
        message += "  Resolution: " + String(resolution) + " bits\n";
        message += "  Duty Cycle: " + String(duty) + "/" + String(maxDuty) +
                   " (" + String((duty * 100) / maxDuty) + "%)";

        cmdParser.sendResponse("gpio", message);
    }
    else
    {
        cmdParser.sendResponse("gpio", "Error: Failed to configure PWM");
        cmdParser.sendResponse("gpio", "Try different parameters or check pin capabilities");
    }
}

// GPIO Servo 控制
void ESP32PeripheralManager::handleGPIOServo(const Command &cmd)
{
    if (isLocked())
    {
        cmdParser.sendResponse("gpio", "Error: Device locked. Use 'unlock' first.");
        return;
    }

    int pin = CommandParser::getNamedArgInt(cmd, "pin", -1);
    int angle = CommandParser::getNamedArgInt(cmd, "angle", 90);

    // 如果没有命名参数，尝试使用位置参数
    if (pin < 0 && cmd.args.size() > 0)
    {
        pin = cmd.args[0].toInt();
        if (cmd.args.size() > 1)
        {
            angle = cmd.args[1].toInt();
        }
    }

    if (pin < 0)
    {
        cmdParser.sendResponse("gpio", "Error: Pin number is required.");
        cmdParser.sendResponse("gpio", "Usage: gpio_servo <pin> [angle]");
        cmdParser.sendResponse("gpio", "Or: gpio_servo --pin <pin> [--angle <0-180>]");
        return;
    }

    if (angle < 0 || angle > 180)
    {
        cmdParser.sendResponse("gpio", "Error: Angle must be between 0-180 degrees");
        return;
    }

    // 使用LEDC模拟Servo（ESP32没有硬件Servo）
    int channel = CommandParser::getNamedArgInt(cmd, "channel", 1);
    int minPulse = CommandParser::getNamedArgInt(cmd, "min_pulse", 500);  // 0.5ms
    int maxPulse = CommandParser::getNamedArgInt(cmd, "max_pulse", 2500); // 2.5ms

    // 计算占空比
    int pulseWidth = map(angle, 0, 180, minPulse, maxPulse);
    int duty = (pulseWidth * 4095) / 20000; // 20ms period

    ledcSetup(channel, 50, 12); // 50Hz, 12-bit resolution
    ledcAttachPin(pin, channel);
    ledcWrite(channel, duty);

    cmdParser.sendResponse("gpio", "Servo configured - Pin: " + String(pin) +
                                       ", Angle: " + String(angle) + "°" +
                                       ", Pulse: " + String(pulseWidth) + "μs");
}
#pragma endregion